package com.im.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.EvaluatorException;
import org.springframework.stereotype.Component;

import com.im.MDA;
import com.yahoo.platform.yui.compressor.CssCompressor;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;

@Component
public class Compressor {

	private static final Logger logger = LogManager.getLogger(Compressor.class);  

	
	// 要处理的目录
	//private static File dir = new File("E:\\js");
	public static String realPath = new String();
	private static int linebreakpos = -1;
	private static boolean munge = true;
	private static boolean verbose = false;
	private static boolean preserveAllSemiColons = false;
	private static boolean disableOptimizations = false;
    
	@PostConstruct
	public static void compressorJsAndCss(){
	
		//WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
		//String realPath = webApplicationContext.getServletContext().getRealPath("/");
		/**
		 * springboot无论以main方法还是spring-boot:run的方式执行都不会跑SpringBootServletInitializer中的onStartup导致
		 * ContextLoaderListener没有执行。原因是在onStartup初始化ContextLoader时使用的是构造函数，没有用ContextLoader.
		 * initWebApplicationContext方式，所以获取不到. 先采取获取固定文件的格式进行获取。
		 */
		//URL url = ClassUtils.getDefaultClassLoader().getResource("application.properties");
		//String realPath = url.getPath().replace("WEB-INF/classes/application.properties", "");
		//需要加载的路劲
		List<String> dirList = MDA.DIR_LIST_FOR_YUICOMPRESSOR;
		if(!"Y".equals(MDA.SWITCH_COMPRESSOR_JS_AND＿CSS)){
			dirList = new ArrayList<>();
		}
		for(String dir : dirList){
			File file = new File(realPath+dir);
			try {
				Compressor.checkFile(file);
			} catch (Exception e) {
				logger.error("压缩文件报错："+e.getMessage());
			}
		}
	}

	public static void main(String[] args) throws Exception {
		//checkFile(dir);
	}

	public static void checkFile(File file){
		File[] files = file.listFiles();
		if (files == null || files.length == 0)
			return;
		for (File f : files) {
			if (f.getName().endsWith(".svn")) {
				continue;
			}
			if (f.isFile()) {
				try {
					jsZip(f);
					logger.info("成功压缩文件：" + f.getName());
				} catch (Exception e) {
					logger.error("压缩文件失败：" + f.getName()+" 原因："+e.getMessage());
				}
				continue;
			} else {
				logger.info("解析目录:" + f.getName());
				checkFile(f);
			}
		}
	}

	public static void jsZip(File file) throws Exception {
		String fileName = file.getName();
		if (!fileName.endsWith(".js") && !fileName.endsWith(".css")) {
			return;
		}
		Reader in = new InputStreamReader(new FileInputStream(file), "utf-8");
		String filePath = file.getAbsolutePath();
		File tempFile = new File(filePath + ".tempFile");
		Writer out = new OutputStreamWriter(new FileOutputStream(tempFile),
				"utf-8");
		if (fileName.endsWith(".js")) {
			JavaScriptCompressor jscompressor = new JavaScriptCompressor(in,
					new ErrorReporter() {
						public void warning(String message, String sourceName,
								int line, String lineSource, int lineOffset) {
							if (line < 0) {
								System.err.println("\n[WARNING] " + message);
							} else {
								System.err.println("\n[WARNING] " + line + ':'
										+ lineOffset + ':' + message);
							}
						}

						public void error(String message, String sourceName,
								int line, String lineSource, int lineOffset) {
							if (line < 0) {
								System.err.println("\n[ERROR] " + message);
							} else {
								System.err.println("\n[ERROR] " + line + ':'
										+ lineOffset + ':' + message);
							}
						}

						public EvaluatorException runtimeError(String message,
								String sourceName, int line, String lineSource,
								int lineOffset) {
							error(message, sourceName, line, lineSource,
									lineOffset);
							return new EvaluatorException(message);
						}
					});
			jscompressor.compress(out, linebreakpos, munge, verbose,
					preserveAllSemiColons, disableOptimizations);
		} else if (fileName.endsWith(".css")) {
			CssCompressor csscompressor = new CssCompressor(in);
			csscompressor.compress(out, linebreakpos);
		}
		out.close();
		in.close();
		file.delete();
		tempFile.renameTo(file);
		tempFile.delete();
	}
	
	
	
 
}
